﻿
using HandyControl.Tools.Extension;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Documents;
using ZFBActivation.Log;

namespace ZFBActivation.Core
{
	public class ProxyHelper
	{
		private static readonly object objLock = new object();

		private static ProxyHelper betLog;

		public static ProxyHelper Instance {
			get {
				if (betLog == null)
					lock (objLock) {
						if (betLog == null) betLog = new ProxyHelper();
					}

				return betLog;
			}
		}

		protected ConcurrentQueue<ProxyInfo> m_Quere = new ConcurrentQueue<ProxyInfo>();




		public async ValueTask<ProxyInfo> GetProxy(string url) {
            //Uri uri = new Uri(url);

            //string query = uri.Query.Substring(1);
            //PostDic pd = new PostDic(query);
            //pd.Set("count", 1);

            //m_Quere.Clear();

            //if (m_Quere.Count > 3) {
            //    return;
            //}
            //string newUrl = url.Substring(0, url.IndexOf("?"));
            //newUrl += "?" + pd.GetBuild();

            HttpItem httpItem = new HttpItem();
            httpItem.URL = url;
            httpItem.Method = MethodEnum.GET;

            var result = await HttpClientHelper.Create(httpItem, "Proxy" + Random.Shared.Next(0, 999)).GetHtmlAsync(httpItem);

            if (result.StatusCode != System.Net.HttpStatusCode.OK) {

                LogHelper.Log(LogDefine.LogVerbose, $"获取代理IP，网络状态异常:{result.StatusCode}", result.Html);
                return null;
            }
            if (string.IsNullOrEmpty(result.Html)) {
                LogHelper.Log(LogDefine.LogVerbose, $"获取代理IP，没有任何返回值:{result.StatusCode}", result.Html);
                return null;
            }
            try {
                JObject job = result.Html.ToObject<JObject>(); ;
                if (job.Value<string>("code") != "200") {
                    LogHelper.Log(LogDefine.LogVerbose, $"获取代理IP，状态码不是200", result.Html);
                    return null;
                }
                var list = job["data"]["proxy_list"] as JArray;
                foreach (var item in list) {
                    var obj = item.ToObject<string>();
                    ProxyInfo info = new ProxyInfo();
                    info.ip = obj.Split(":")[0];
                    info.port = obj.Split(":")[1];
                    return info;
                }
                return null;
            }
            catch (Exception ex) {
                LogHelper.Log(LogDefine.LogVerbose, $"获取代理IP，序列化异常", result.Html);
            }
            return null;
		}
	}
	public class ProxyInfo {
		public string ip { get; set; }
		public string sever { get; set; }
		public string port { get; set; }
		public string net_type { get; set; }

	}
}
